package controllers

import play._
import play.mvc._

import models._
import dao.{PostDAO, UserDAO}

object PostREST extends Controller {

   import views.Rest._
   import config.Services._
   
  def byUserName(username:String, format:String, limit:Short=0, page:Short=1) = {
    using(dbSession){ s =>
      outputPostList(PostDAO.findByAuthorName(username, limit, page), format)
    }
  }
   
  def byCategory(catId:Int, format:String, limit:Short=0, page:Short=1) = { //FIXME: guard
    using(dbSession){ s =>
      outputPostList(PostDAO.findByCategory(Post.Category(catId), limit, page), format)
    }
  }
   
  def byYear(year:Short, format:String, limit:Short=0, page:Short=1) = { //FIXME: validation
    using(dbSession){ s =>
      outputPostList(PostDAO.findByYear(year, limit, page), format)
    }
    
  }
   
  def byYearAndCategory(year:Short, category:Short, format:String, limit:Short=0, page:Short=1) = { //FIXME: y+c validation
    using(dbSession){ S =>
      outputPostList(PostDAO.findByYearAndCategory(year, Post.Category(category), limit, page), format)
    }
  }
   
  def latest(limit:Short, format:String) = {
    using(dbSession){ s =>
      outputPostList(PostDAO.findLatests(limit), format)
    }
  }
   
  private def outputPostList(ps:Option[List[Post]], format:String) = {
    if(format == "htm"){
        Html( ps.map( html posts _ ).getOrElse( <ul />) )
      } else if(format == "xml"){
        Xml( ps.map( html postsXml _ ).getOrElse("""<entries />""") )
      }
  }
   
  def post(id:Long, format:String) = {
    using(dbSession){ s =>
      val p = PostDAO.findByID(id)
      val logedUser = session("username")
      if(format == "htm"){
        Html( p.map { html.post(_, session("username") ) } getOrElse ( <div>No encontrado</div> ) )
      } else if(format == "xml"){
        Xml( p.map( html postXml _ ).getOrElse( <post /> ) )
      }
    }
  }
   
  def comet(format:String) = {
    using(dbSession){ s =>
      val posts = PostDAO.findLaterThan(request.date)
      if(posts.isDefined){
        outputPostList(posts, format)
      } else {
        Suspend("3s")
      }
    }
  }
  
  def comments(pid:Long, format:String) = {
    using(dbSession){ s =>
      PostDAO.findByID(pid) match {
        case Some(p)   => html.comments( p.getComments() )
        case None      => html.comments( None ) // TODO: Indicar que el post no existe
      }
    }
  }

}
